//
//  StateParser.m
//  RestaurantX
//
//  Created by Nguyen Thanh Hai on 7/19/12.
//  Copyright (c) 2012 _eBars GbR_. All rights reserved.
//

#import "StateParser.h"
#import "SBJSON.h"

@implementation StateParser
@synthesize resultDict;
@synthesize resultData;
@synthesize delegate;

- (void) dealloc{
    [resultDict release];
    [resultData release];
    [theConnection release];
    [super dealloc];
}

- (void)getStateWithDelegate:(id) theDelegate{
    self.delegate = theDelegate;
    //NSLog(@"RQ URL = %@",[NSString stringWithFormat:@"%@%@?token=%@",kLoginWS,phoneNumber,base64Key]);
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:StateList]];
    theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    resultData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.resultData appendData:data];
}

- (void)connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error{
    //NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    [delegate didEndStateParser:resultDict success:NO];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    SBJSON *jsonParser = [[[SBJSON alloc] init] autorelease];
    NSString *jsonFileContent = [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];
    resultDict = [[NSArray alloc]init];
    resultDict = [(NSArray*)[jsonParser objectWithString:jsonFileContent error:nil] retain];
    [delegate didEndStateParser:resultDict success:YES];
}

@end
